package router

import (
	"day116/handler"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Init() *gin.Engine {
	r := gin.Default()
	r.Use(Cors())
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	user := r.Group("/user")
	{
		user.POST("/login", handler.Login)
		user.POST("/addUserRole", handler.AddUserRole)
		user.POST("/addRoleNode", handler.AddRoleNode)
		user.GET("/userRoleList", handler.UserRoleList)
		user.GET("/roleNodeList", handler.RoleNodeList)
	}
	order := r.Group("/order")
	{
		order.POST("/merhouseAdd", handler.MerHouseAdd)
		order.POST("/orderAdd", handler.OrderAdd)
		order.GET("/detail", handler.Detail)
		order.GET("/list", handler.List)
	}
	users := r.Group("/users")
	{
		users.POST("/logins", handler.Logins)
		users.POST("/userAddRole", handler.UserAddRole)
		users.POST("/roleAddNode", handler.RoleAddNode)
		users.GET("/roleList", handler.RoleList)
		users.GET("/nodeList", handler.NodeList)
	}
	return r
}
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
